package com.xd.study.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.xd.study.R;

/**
 * Created by DGF on 2015/5/6.
 */
public class GestureDetectorActivity extends Activity {

    class MyGestureListener extends GestureDetector.SimpleOnGestureListener{

        /**
         * 滑动
         * @param e1
         * @param e2
         * @param velocityX
         * @param velocityY
         * @return
         */
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

            if (e1.getX() - e2.getX() > 50){
                Toast.makeText(GestureDetectorActivity.this, "从右往左滑", Toast.LENGTH_SHORT).show();
            }else if (e1.getX() - e2.getX() < -50){
                Toast.makeText(GestureDetectorActivity.this, "从左往右滑", Toast.LENGTH_SHORT).show();
            }

            return super.onFling(e1, e2, velocityX, velocityY);
        }
    }

    GestureDetector gestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gesture_detector);

        gestureDetector = new GestureDetector(this, new MyGestureListener());

        ImageView imageView = (ImageView)findViewById(R.id.gesture_detector_image);

        /**
         * 使用GestureDetector进行手势识别的手势交互过程：
         * 1、触屏一霎那，触发MotionEvent事件
         * 2、被OnTouchListener监听，在onTouch中获得MotionEvent对象
         * 3、GestureDetector转发MotionEvent对象到OnGestureListener
         * 4、OnGestureListener获得该对象，根据该对象封装的信息做出合适的反馈
         */
        imageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                gestureDetector.onTouchEvent(event);
                return true;
            }
        });
    }
}
